package com.sgg.algorithm.sort;

import java.util.Arrays;

public class RadixSort {
    public static void main(String[] args) {
        int[] arr = {53, 3, 542, 748, 14, 214};
        sort(arr);
        System.out.println(Arrays.toString(arr));

    }

    public static void sort(int[] arr) {
        int max = arr[0];
        for (int i = 1; i < arr.length - 1; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }
        int loopSize = (max + "").length();
        int[][] bucket = new int[10][arr.length];
        int[] counts = new int[10];

        for (int loop = 0, y = 1; loop < loopSize; loop++, y *= 10) {
            for (int j = 0; j < arr.length; j++) {
                int mo = arr[j] / y % 10;
                bucket[mo][counts[mo]] = arr[j];
                counts[mo]++;
            }
            int index = 0;
            for (int i = 0; i < 10; i++) {
                if (bucket[i].length > 0) {
                    for (int j = 0; j < counts[i]; j++) {
                        arr[index] = bucket[i][j];
                        index++;
                    }
                }
                counts[i] = 0;
            }
//            System.out.println(Arrays.toString(arr));
        }
    }

    public static void demo(int[] arr) {
        int[][] bucket = new int[10][arr.length];
        int[] counts = new int[10];
        //1
        for (int j = 0; j < arr.length; j++) {
            int mo = arr[j] % 10;
            bucket[mo][counts[mo]] = arr[j];
            counts[mo]++;
        }
        int index = 0;
        for (int j = 0; j < 10; j++) {
            if (bucket[j].length > 0) {
                for (int k = 0; k < counts[k]; k++) {
                    arr[index] = bucket[k][k];
                    index++;
                }
            }
            counts[j] = 0;
        }
        //2
        for (int j = 0; j < arr.length; j++) {
            int mo = arr[j] / 10 % 10;
            bucket[mo][counts[mo]] = arr[j];
            counts[mo]++;
        }
        index = 0;
        for (int i = 0; i < 10; i++) {
            if (bucket[i].length > 0) {
                for (int j = 0; j < counts[i]; j++) {
                    arr[index] = bucket[i][j];
                    index++;
                }
            }
            counts[i] = 0;
        }
        //3
        for (int j = 0; j < arr.length; j++) {
            int mo = arr[j] / 100 % 10;
            bucket[mo][counts[mo]] = arr[j];
            counts[mo]++;
        }
        index = 0;
        for (int i = 0; i < 10; i++) {
            if (bucket[i].length > 0) {
                for (int j = 0; j < counts[i]; j++) {
                    arr[index] = bucket[i][j];
                    index++;
                }
            }
            counts[i] = 0;
        }
    }
}
